package com.jelly.web.share.home;

import com.jelly.common.constant.Constant;
import com.jelly.common.util.StringUtils;
import com.jelly.common.util.bean.LogBeanUtil;
import com.jelly.common.util.web.AjaxPostResponse;
import com.jelly.common.util.web.RequestContextHolderUtil;
import com.jelly.config.shiro.token.ShiroToken;
import com.jelly.config.shiro.token.TokenUtil;
import com.jelly.web.share.base.controller.BaseController;
import com.jelly.web.modules.staff.user.domain.User;
import com.jelly.web.modules.staff.user.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

/**
 * @创建人 ql
 * @创建时间 2018-07-31 16:17
 * @项目名称 jelly
 * @功能描述: 后台登录控制器
 **/
@Controller
@RequestMapping("/login")
public class LoginController extends BaseController {

    @Autowired
    private IUserService userService;

    /**
     * 登录页面跳转控制
     * @return
     */
    @GetMapping
    public String getlogin(){
        return "/login";
    }

    /**
     *  验证用户名密码
     * @param account       用户名
     * @param password      密码
     * @param rememberMe    记住我
     * @return
     */
    @PostMapping
    @ResponseBody
    public ResponseEntity<AjaxPostResponse> login(String account, String password, Boolean rememberMe){

        //验证用户是否为空
        if(StringUtils.isBlank(account)){

            return errorResponse("用户名不能为空");

        }
        //验证密码否为空
        if(StringUtils.isBlank(password)){

            return errorResponse("密码不能为空");

        }

        try {
            //账号密码交给shiro进行验证
            ShiroToken token = new ShiroToken(account, password);
            //记住我：true，false
            token.setRememberMe(rememberMe == null ?false:true);

            /**获取请求的subject
             * SecurityUtils.getSubject()是每个请求创建一个Subject,
             * 并保存到ThreadContext的resources（ThreadLocal<Map<Object, Object>>）
             * 变量中，也就是一个http请求一个subject,并绑定到当前线程。
             */
            Subject subject = SecurityUtils.getSubject();
            //登陆认证
            subject.login(token);
            //设置登录成功日志
            LogBeanUtil.loginLogMsg(account,"登录成功", Constant.SUCCESS);
            //更新用户信息
            User user = TokenUtil.getToken();

            user.setLoginDate(new Date());

            user.setLoginCount(user.getLoginCount()+1);

            user.setLoginIp(RequestContextHolderUtil.getIPAddress());

            userService.updateUser(user);

            return okResponse("");

        }catch (UnsupportedTokenException e) {

            LogBeanUtil.loginLogMsg(account,e.getMessage(), Constant.ERROR);
            return errorResponse(e.getMessage());

        }catch (UnknownAccountException e){
            LogBeanUtil.loginLogMsg(account,e.getMessage(), Constant.ERROR);
            return errorResponse(e.getMessage());

        }catch (DisabledAccountException e){
            LogBeanUtil.loginLogMsg(account,e.getMessage(), Constant.ERROR);
            return errorResponse(e.getMessage());

        }catch (ExcessiveAttemptsException e){
            LogBeanUtil.loginLogMsg(account,e.getMessage(), Constant.ERROR);
            return errorResponse(e.getMessage());

        }catch (AuthenticationException e){

            LogBeanUtil.loginLogMsg(account,"密码错误", Constant.ERROR);
            return errorResponse("密码错误");

        }catch (Exception e){

            LogBeanUtil.loginLogMsg(account,"账号密码错误", Constant.ERROR);
            return errorResponse("账号密码错误");

        }

    }

}
